<!-- 需求列表  -->
<template>
  <pageHeader title="生产计划" :breadCrumb="['生产管理', '生产计划']" />
  <a-tabs v-model:active-key="searchForm.type" @change="tableRef.loadData()">
    <a-tab-pane :key="2" title="月计划" />
    <a-tab-pane :key="1" title="周计划" />
  </a-tabs>
  <div class="cantainer">
    <div class="tableForm">
      <a-space>
        <a-month-picker
          v-model="nowDate"
          value-format="Date"
          v-if="searchForm.type == 2"
        />
        <a-week-picker
          v-model="nowDate"
          value-format="Date"
          :day-start-of-week="1"
          v-else
        />
        <ProductChoice
          v-model:value="searchForm.product"
          @choice="productChoice"
        />
        <a-button type="outline" @click="resetting">
          <template #icon> <icon-refresh /> </template>重置
        </a-button>
      </a-space>

      <a-space>
        <!-- <a-button type="primary" @click="toDetails('add')">
          <template #icon>
            <icon-plus />
          </template>
          新增工位
        </a-button> -->
        <!-- </a-button> -->
        <a-button
          v-show="searchForm.type === 1"
          type="outline"
          @click="jumpAddProductionTask"
        >
          <template #icon>
            <icon-plus />
          </template>
          创建生产任务
        </a-button>

        <HeaderSettingCopy
          v-model:headerValues="headerValues"
          :define-headers="OrderPlanningHerders.herders"
          :type="OrderPlanningHerders.type"
        />
      </a-space>
    </div>
    <tableTurn
      :tableData="getDemandAll"
      ref="tableRef"
      :args="{
        rowSelection:
          searchForm.type === 1
            ? {
                type: 'radio',
              }
            : false,
      }"
    >
      <a-table-column :width="70" align="center" title="序号">
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        v-for="header in headerValues"
        :key="header.name"
        :width="header.width || 200"
        :title="header.name"
        :fixed="header.fixed"
        :data-index="header.code"
        align="center"
        :ellipsis="true"
        :tooltip="{
          position: 'top',
        }"
      >
        <template #cell="{ record }" v-if="!header.code">
          <template v-if="header.name === '物料属性'">
            {{
              record.materialAttribute === 1
                ? '自制'
                : record.materialAttribute === 2
                ? '委外'
                : record.materialAttribute === 3
                ? '虚拟'
                : '采购'
            }}
          </template>
          <template v-if="header.name === '计划数量'">
            {{
              record.data.reduce(
                (num: number, { number }: any) => num + number,
                0
              ) || 0
            }}
          </template>
        </template>
      </a-table-column>
      <a-table-column
        :title="Dayjs(nowDate).format('YYYY 年 MM 月')"
        align="left"
      >
        <a-table-column
          v-for="(item, index) in dayList"
          :key="index"
          :width="70"
          align="center"
          :title="item.toDate().getDate() + '号'"
        >
          <template #title>
            <div>{{ item.toDate().getDate() + '号' }}</div>
            <div>{{
              ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][
                item.day()
              ]
            }}</div>
          </template>
          <template #cell="{ record }">
            {{ getNumber(item, record.data || []) }}
          </template>
        </a-table-column>
      </a-table-column>
      <a-table-column :width="100" fixed="right" title="操作" align="center">
        <template #cell="{ record }">
          <!-- <a-space>
            <a-link @click="toDetails('edit', record)"> 编辑计划 </a-link>
            <a-link
              @click="monthToWeeK('edit', record)"
              v-if="searchForm.type === 2"
            >
              创建周计划
            </a-link>
            <a-link @click="toPlanWorkShopAdd(record)" v-else>
              创建车间计划
            </a-link>
            <a-link
              :disabled="record.state === 2"
              @click="toAddMaterialPicking(record.id)"
            >
              创建生产领料
            </a-link>
          </a-space> -->
          <a-space :size="40">
            <!-- <a-dropdown>
              <a-link type="text">更多功能</a-link>
              <template #content>
                <a-doption type="text" @click="toDetails('edit', record)">
                  编辑计划
                </a-doption>
                <a-doption
                  @click="monthToWeeK('edit', record)"
                  v-if="searchForm.type === 2"
                  :disabled="verifyNumber(record.data || [])"
                >
                  创建周计划
                </a-doption>
                <a-doption
                  @click="toPlanWorkShopAdd(record)"
                  v-else
                  :value="{ value: 'Option3' }"
                  :disabled="verifyNumber(record.data || [])"
                  >创建车间计划
                </a-doption>
                <a-doption
                  v-if="searchForm.type == 1 && record.materialAttribute === 1"
                  :disabled="
                    record.state === 2 || verifyNumber(record.data || [])
                  "
                  @click="toAddMaterialPicking(record)"
                  >创建生产领料</a-doption
                >
                <a-doption
                  v-if="record.materialAttribute === 2 && searchForm.type == 1"
                  :disabled="
                    record.outsourcingAmount === record.totalNum ||
                    verifyNumber(record.data || [])
                  "
                  @click="ToTransferOutsourcing(record)"
                  >创建产品委外</a-doption
                >
              </template>
            </a-dropdown> -->

            <a-tooltip content="更多功能">
              <a-dropdown>
                <IconFont
                  type="icon-more-def"
                  :size="26"
                  :style="{
                    marginRight: '10px',
                    cursor: 'pointer',
                  }"
                />
                <template #content>
                  <a-doption type="text" @click="toDetails('edit', record)">
                    编辑计划
                  </a-doption>
                  <a-doption
                    @click="monthToWeeK('edit', record)"
                    v-if="searchForm.type === 2"
                    :disabled="verifyNumber(record.data || [])"
                  >
                    创建周计划
                  </a-doption>
                  <a-doption
                    @click="toPlanWorkShopAdd(record)"
                    v-else
                    :value="{ value: 'Option3' }"
                    :disabled="verifyNumber(record.data || [])"
                    >创建车间计划
                  </a-doption>
                  <a-doption
                    v-if="
                      searchForm.type == 1 && record.materialAttribute === 1
                    "
                    :disabled="
                      record.state === 2 || verifyNumber(record.data || [])
                    "
                    @click="toAddMaterialPicking(record)"
                    >创建生产领料</a-doption
                  >
                  <a-doption
                    v-if="
                      record.materialAttribute === 2 && searchForm.type == 1
                    "
                    :disabled="
                      record.outsourcingAmount === record.totalNum ||
                      verifyNumber(record.data || [])
                    "
                    @click="ToTransferOutsourcing(record)"
                    >创建产品委外</a-doption
                  >
                </template>
              </a-dropdown>
            </a-tooltip>
            <!-- <a-link status="danger"> 删除 </a-link> -->
          </a-space>
        </template>
      </a-table-column>
    </tableTurn>
    <!-- <Calendar>
      <template #day><a-input-number :min="1" /></template>
    </Calendar> -->
    <PlanProductionModal
      ref="refPlanProductionModal"
      @ok="tableRef.loadData()"
    />
    <MonthToWeeKModal ref="refMonthToWeeKModal" @ok="tableRef.loadData()" />
  </div>
</template>

<script lang="ts" setup>
  import { reactive, onMounted, ref, computed } from 'vue';
  import { useRouter } from 'vue-router';
  import { useProduceStore } from '@/store';
  import {
    GetProducePlanPage,
    GetWorkOrderPage,
  } from '@/api/produce-management/OrderPlanning';
  import Dayjs from 'dayjs';
  import { OrderPlanningHerders } from '@/utils/tableHerders';
  import { Message } from '@arco-design/web-vue';
  import { cloneDeep } from 'lodash';
  import PlanProductionModal from './PlanProductionDetails/PlanProductionModal.vue';
  import MonthToWeeKModal from './MonthToWeeKModal.vue';

  const store = useProduceStore();
  const router = useRouter();
  let searchForm = reactive<any>({ type: 2 });
  const tableRef = ref();

  let toPlanWorkShopAdd = (data: any) => {
    localStorage.setItem('PlanProductionForm', JSON.stringify(data));
    router.push({ name: 'PlanWorkShopAdd' });
  };
  let productChoice = async ({ id }: any) => {
    let res = await GetWorkOrderPage({ page: 1, size: -1, keyWord: id });
  };
  let refModal = ref();
  let refPlanProductionModal = ref();
  const toDetails = (mode: string, data?: any) => {
    refPlanProductionModal.value.setData(data);
  };
  let refMonthToWeeKModal = ref();
  const monthToWeeK = (mode: string, data?: any) => {
    refMonthToWeeKModal.value.setData(data);
  };

  let nowDate = ref(new Date());
  let dayList = computed(() => {
    let { type } = searchForm;
    let list = [];
    let getNowDate = Dayjs(nowDate.value);
    if (type === 2) {
      let monthStart = getNowDate.startOf('M');
      let centerNum = getNowDate.endOf('M').toDate().getDate();
      for (let i = 0; i < centerNum; i += 1) {
        list.push(monthStart.add(i, 'd'));
      }
    } else {
      let day = getNowDate.day();
      let startDate = day
        ? getNowDate.subtract(day, 'd')
        : getNowDate.add(day, 'd');
      for (let i = 0; i < 7; i += 1) {
        list.push(startDate.add(i + 1, 'd'));
      }
    }
    return list;
  });
  let getNumber = (dateItem: any, list: any[]) => {
    return list.find(({ date }) => {
      if (!date) return false;
      return dateItem.isSame(Dayjs(date), 'day');
    })?.number;
  };

  const getDemandAll = async (page: any) => {
    try {
      let res = await GetProducePlanPage({
        ...page,
        ...searchForm,
      });
      return Promise.resolve(res);
    } catch (err: unknown) {
      return Promise.reject();
    }
  };

  const verifyNumber = (data: any[]) => {
    let sum = 0;
    dayList.value.forEach((ele) => {
      sum += getNumber(ele, data) ? getNumber(ele, data) : 0;
    });
    if (sum) return false;
    return true;
  };

  const Search = () => {
    tableRef.value.loadData();
  };
  const resetting = () => {
    for (const key in searchForm) {
      delete searchForm[key];
    }
    tableRef.value.loadData();
  };
  const del = async (id: number) => {
    // await DelStation({ id });
    tableRef.value.loadData();
  };

  let headerValues = ref<any[]>([]);
  const jumpAddProductionTask = () => {
    if (tableRef.value.selectedKeys?.length === 1) {
      const data = cloneDeep(tableRef.value.selectedList[0]);
      if (verifyNumber(data?.data || [])) {
        return Message.error('请重新选择周计划');
      }
      data.produceNumber =
        data?.data?.reduce((num: number, { number }: any) => num + number, 0) ||
        0;
      localStorage.setItem('weeklyPlanData', JSON.stringify(data));
      router.push({
        name: 'AddProductionTask',
      });
    } else {
      Message.error('请选择周计划');
    }
  };

  const toAddMaterialPicking = (val: any) => {
    const { id, canPickAmount, state } = val;
    router.push({
      name: 'AddMaterialPicking',
      query: { id, canPickAmount, state },
    });
  };

  const ToTransferOutsourcing = (val: any) => {
    // store.addOutsourcingForm = val;
    sessionStorage.setItem('TransferOutsourcing', JSON.stringify(val));
    router.push({ name: 'TransferOutsourcing' });
  };
</script>

<style scoped lang="less">
  .cantainer {
    padding: 20px;
    padding-top: 0;
  }
  .tableForm {
    display: flex;
    justify-content: space-between;
    margin-bottom: 15px;
  }
</style>
